<script type="text/javascript">
$('document').ready(function(){

	function updateSectorLocations(first_load){
		var vals = '';
		var i = 0;
		$('.sf_admin_form_field_code_sector_list input[type="checkbox"]').each(function(){
			if($(this).attr('checked') == true){
				vals += $(this).val()+'-';
			}
		});
		showLoadingImage('program_location_of_holding');
		$.ajax({
			url:     '<?php echo url_for('location/getBySectorIds'); ?>',
			type:    'get',
			data:    { 'sector_ids': vals},
			success: function(data){
				
				var res_ids = '';
				
				var res = '('+data+')';
				res = eval(res);

				$('#program_location_of_holding').html('');
				var res_html = '<option value=""></option>';
				for(x in res){
					var row = res[x];
					if(row instanceof Object){
					res_html += '<optgroup label="'+x+'">';
					for(y in row){
						res_ids += ' '+y;
						res_html += '<option value="'+y+'">'+row[y]+'</option>';
					}
					res_html += '</optgroup>';
					}else{
						res_ids += ' '+x;
						res_html += '<option value="'+x+'">'+row+'</option>';
					}
				}
				res_html += '<option value="other">اخرى</option>';
				$('#program_location_of_holding').html(res_html);

				if(first_load){
					var def_loc_val = '<?php echo $form->getValue('location_of_holding')?$form->getValue('location_of_holding'):$form->getObject()->getLocationOfHolding(); ?>';
				//	console.log(res_ids);
				//	console.log(res_ids.indexOf(def_loc_val));
					if( res_ids.indexOf(def_loc_val) != -1)
					{
						$('#program_location_of_holding').val(def_loc_val);
					}else{
						$('#other_program_location_of_holding').val(def_loc_val);
						$('#program_location_of_holding').val('other');
						$('#program_location_of_holding').trigger('change');
					}
				}
				
				removeLoadingImage('program_location_of_holding');
			}

		});

	}

	$('.sf_admin_form_field_code_sector_list input[type="checkbox"]').click(function(){
		updateSectorLocations(false);
	});
	updateSectorLocations(true);
});
</script>